package com.fudan.backend.controller;

import com.fudan.backend.exception.RetCode;
import com.fudan.backend.pojo.Commodity;
import com.fudan.backend.pojo.statics.CommodityStatus;
import com.fudan.backend.service.CommodityService;
import com.fudan.backend.util.R;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;

@RestController
@RequestMapping("/commodity")
public class CommodityController {
    @Autowired
    CommodityService commodityService;

    @GetMapping("/info/{commodityId}")
    public R getCommodityByCommodityId(@PathVariable("commodityId") String commodityId) {
        Commodity commodity = commodityService.getCommodityByCommodityId(commodityId);
        return new R(RetCode.COMMODITY_SUCCESS.getCode(), RetCode.COMMODITY_SUCCESS.getMessage(), RetCode.COMMODITY_SUCCESS.getMessage(), commodity);
    }

    @GetMapping("/store/{storeId}")
    public R getAllCommodityByStoreId(int current, int size, @PathVariable("storeId") String storeId) {
        PageInfo<Commodity> page = commodityService.getAllCommodityByStoreId(current, size, storeId);
        HashMap<String, Object> map = new HashMap<>();
        map.put("commodityList", page.getList());
        map.put("total", page.getTotal());
        return new R(RetCode.COMMODITY_SUCCESS.getCode(), RetCode.COMMODITY_SUCCESS.getMessage(), RetCode.COMMODITY_SUCCESS.getMessage(), map);
    }

    @GetMapping("/info")
    public R getAllCommodity(int current, int size) {
        PageInfo<Commodity> page = commodityService.getAllCommodity(current, size);
        HashMap<String, Object> map = new HashMap<>();
        map.put("commodityList", page.getList());
        map.put("total", page.getTotal());
        return new R(RetCode.COMMODITY_SUCCESS, map);
    }

    @PostMapping("/off-shelf/{commodityId}")
    public R offShelfCommodity(@PathVariable("commodityId") String comodityId) {
        commodityService.setCommodityStatus(comodityId, CommodityStatus.REMOVED);
        return new R(RetCode.COMMODITY_SUCCESS);
    }

    @GetMapping("/activity/{activityId}")
    public R getAllCommodityByActivityId(int current, int size, @PathVariable("activityId") String activityId) {
        List<Commodity> commodityList = commodityService.getAllCommodityByActivityId(activityId);
        int startElement = (current - 1) * size;
        HashMap<String, Object> map = new HashMap<>();
        if(commodityList.size() != 0) {
            size = Math.min(size, commodityList.size());
            map.put("commodityList", commodityList.subList(startElement, startElement + size));
        } else {
            map.put("commodityList", commodityList);
        }
        map.put("total", commodityList.size());
        return new R(RetCode.COMMODITY_SUCCESS, map);
    }
}
